# ------------------------------------------------------------------------------------------------
### Generate Figure 14: Effects by government unit passing the resolution
# ------------------------------------------------------------------------------------------------

# Load data
load("../data/results/sdid_results.Rda")

# Define the outcomes to plot with their display names
outcome_mapping <- c(
  "Opposition" = "Opposition Turnout",
  "Law and Justice (PiS)" = "Government Turnout", 
  "Overall Turnout" = "Overall Turnout"
)

# Filter and prepare data 
plot_data <- sdid_results %>%
  filter(
    # Filter for main analysis (Any Level, Any Type, not Any Level, notyettreated, Full Sample)
    sum_level == "Any Level" & 
    sum_type == "Any Type" & 
    level != "Any Level" & 
    type == "Any Type" & 
    control_sample == "notyettreated" & 
    no300k_sample == "Full Sample" & 
    noproposed_sample == "Full Sample",
    # Filter for main outcomes
    (party == "Opposition" & outcome == "Party Turnout") |
    (party == "Law and Justice (PiS)" & outcome == "Party Turnout") |
    (party == "Overall Turnout" & outcome == "Overall Turnout")
  ) %>%
  mutate(
    outcome = outcome_mapping[party],
    outcome = factor(outcome, levels = c("Government Turnout", "Opposition Turnout", "Overall Turnout")),
    level = factor(level, levels = c("Province Level", "County Level", "Municipality Level"))
  )

# Generate plot
ggplot(plot_data, aes(x = estimate, y = outcome)) +
  # Confidence intervals (99%, 95%, 90%) with decreasing linewidth
  geom_errorbarh(aes(xmin = lower_cb_99, xmax = upper_cb_99), height = 0, linewidth = 1, alpha = 0.5, position = position_dodge(0.3)) +
  geom_errorbarh(aes(xmin = lower_cb_95, xmax = upper_cb_95), height = 0, linewidth = 3, alpha = 0.3, position = position_dodge(0.3)) +
  geom_errorbarh(aes(xmin = lower_cb_90, xmax = upper_cb_90), height = 0, linewidth = 5, position = position_dodge(0.3)) +
  # Point estimates
  geom_point(shape = 21, fill = "white", size = 3, stroke = 1.5, position = position_dodge(0.3)) +
  # Faceting and styling
  facet_grid(cols = vars(level), scales = "fixed") +
  labs(x = "Percentage points") +
  geom_vline(xintercept = 0, linetype = "dotted") +
  theme_bw() +
  theme(
    legend.position = "bottom", 
    axis.title.y = element_blank(), 
    panel.grid.major.y = element_blank(), 
    text = element_text(size = 23)
  )

# Save the plot
ggsave("../output/plots/figure14.pdf", width = 14, height = 5, dpi = 700)

